using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Globalization;
using Medianamik.UI.Lock;
using Telerik.Web.UI;

namespace Medianamik.UI.Web.MVP.View.UserControls
{
    public partial class MedianamikGrid : UserControlModuleView, IMedianamikGrid
    {
        public event EventHandler<ActivationStatusChangedEventArgs> ActivationStatusChanged;
        public event EventHandler<IdEventArgs> LockRequestFailed;
        public event EventHandler<GridPageSizeChangedEventArgs> PageSizeChanged;
        public event EventHandler<GridPageChangedEventArgs> PageIndexChanged;
        public event EventHandler<GridItemEventArgs> GridDataBound;
        public event EventHandler<GridItemEventArgs> GridCreating;
        public event EventHandler<OrderChangedEventArgs> OrderChanged;
        public event EventHandler NodeDeleted;

        protected void Page_Init(object sender, EventArgs e)
        {
            Grid.ItemCreated += OnGridItemCreated;
            Grid.ItemDataBound += OnGridItemDataBound;
            Grid.PageSizeChanged += OnPageSizeChanged;
            Grid.PageIndexChanged += OnPageIndexChanged;
            Grid.RowDrop += OnOrderChanged;
        }

        private void OnGridItemCreated(object sender, GridItemEventArgs e)
        {
            if (GridCreating != null)
                GridCreating(sender, e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            RadAjaxManager.GetCurrent(Page).AjaxRequest += OnNodeDeleted;
        }

        void OnNodeDeleted(object sender, EventArgs e)
        {
            if (NodeDeleted != null)
                NodeDeleted(sender, null);
        }

        void OnOrderChanged(object sender, GridDragDropEventArgs e)
        {
            if (e.DraggedItems[0].OwnerGridID == Grid.ClientID && string.IsNullOrEmpty(e.HtmlElement))
            {
                var dataKeyName = Grid.MasterTableView.DataKeyNames.FirstOrDefault();

                var id = e.DraggedItems[0].GetDataKeyValue(dataKeyName ?? "NodeId") as Guid?;
                var destinationId = e.DestDataItem.GetDataKeyValue(dataKeyName ?? "NodeId") as Guid?;

                if (id.HasValue && destinationId.HasValue && OrderChanged != null)
                    OrderChanged(sender, new OrderChangedEventArgs(id.Value, destinationId.Value,
                        e.DropPosition == GridItemDropPosition.Above
                        ? DropPosition.Above : DropPosition.Below));
            }
        }

        void OnPageIndexChanged(object source, GridPageChangedEventArgs e)
        {
            if (PageIndexChanged != null)
                PageIndexChanged(null, e);
        }

        void OnPageSizeChanged(object source, GridPageSizeChangedEventArgs e)
        {
            if (PageSizeChanged != null)
                PageSizeChanged(null, e);
        }

        void OnGridItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                var lbl = e.Item.FindControl("ChangePageSizeLabel") as Label;
                if (lbl != null)
                    lbl.Text = Translator.Translate("Medianamik_Global", "GridChangePageSize");
            }

            if (GridDataBound != null)
                GridDataBound(sender, e);
        }

        protected void OnNodeActivation(object sender, CommandEventArgs e)
        {
            if (ActivationStatusChanged != null)
                ActivationStatusChanged(sender,
                    new ActivationStatusChangedEventArgs(new Guid(e.CommandArgument.ToString()),
                        e.CommandName.ToLowerInvariant() == "activate" ?
                            ActiveStatus.Activated : ActiveStatus.Deactivated, CurrentCulture));
        }

        protected void OnLockRequestFailed(object sender, CommandEventArgs e)
        {
            if (LockRequestFailed != null)
                LockRequestFailed(sender, new IdEventArgs(e.CommandArgument.ToString()));
        }

        public IEnumerable<object> DataSource
        {
            set
            {
                Grid.DataSource = value;
                Grid.DataBind();
                //GridUpdatePanel.Update();
            }
        }

        public void UpdateGrid()
        {
            GridUpdatePanel.Update();
        }

        public LockInfoToolTip LockInfoTooltip { get { return GridLockInfoTooltip; } }

        public int PageSize
        {
            get { return Grid.PageSize; }
            set { Grid.PageSize = value; }
        }

        public int PageIndex
        {
            get
            {
                return Grid.CurrentPageIndex + 1;
            }
            set { Grid.CurrentPageIndex = value - 1; }
        }

        public int TotalCount
        {
            set { Grid.VirtualItemCount = value; }
        }

        public bool AllowPaging
        {
            get { return Grid.AllowPaging; }
            set { Grid.AllowPaging = value; }
        }

        public bool AllowSorting
        {
            get { return Grid.AllowSorting; }
            set
            {
                Grid.AllowSorting = value;

                if (value)
                {
                    Grid.MasterTableView.ItemStyle.CssClass = "DragCursor";
                    Grid.ClientSettings.AllowRowsDragDrop = true;
                    Grid.ClientSettings.EnableRowHoverStyle = true;
                    Grid.ClientSettings.Selecting.AllowRowSelect = true;
                    Grid.ClientSettings.Selecting.EnableDragToSelectRows = true;
                }
                else
                {
                    Grid.MasterTableView.ItemStyle.CssClass = "";
                    Grid.ClientSettings.AllowRowsDragDrop = false;
                    Grid.ClientSettings.EnableRowHoverStyle = false;
                    Grid.ClientSettings.Selecting.AllowRowSelect = false;
                    Grid.ClientSettings.Selecting.EnableDragToSelectRows = false;
                }
            }
        }

        public string[] DataKeyNames
        {
            get { return Grid.MasterTableView.DataKeyNames; }
            set { Grid.MasterTableView.DataKeyNames = value; }
        }

        public virtual string EditReturnUrl
        {
            get { return (String)(ViewState["EditReturnUrl"] ?? ""); }
            set { ViewState["EditReturnUrl"] = value; }
        }

        public virtual string EditPageUrl
        {
            get { return (String)(ViewState["EditPageUrl"] ?? ""); }
            set { ViewState["EditPageUrl"] = value; }
        }

        protected virtual CultureInfo CurrentCulture { get { return Page.CurrentEditionCulture; } }
    }
}